#include "volumetool.h"
#include "ui_volumetool.h"

#include <QGraphicsDropShadowEffect>
#include <QPainter>
#include <QEvent>


VolumeTool::VolumeTool(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::VolumeTool)
    , isMuted(false)
{
    ui->setupUi(this);

    ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));

    setWindowFlags(Qt::Popup|Qt::FramelessWindowHint);

    setAttribute(Qt::WA_TranslucentBackground);

    ui->volumeRatio->setText("20%");
    QRect rect = ui->outLine->geometry();
    ui->outLine->setGeometry(rect.x(), rect.height() - 36 + 25, rect.width(), 36);
    ui->sliderBtn->move(ui->sliderBtn->x(), ui->outLine->y() - ui->sliderBtn->height() / 2);

    connect(ui->silenceBtn, &QPushButton::clicked, this, [=](){
        isMuted = !isMuted;

        if(isMuted)
            {
            ui->silenceBtn->setIcon(QIcon(":/images/silent.png"));
        }
        else
            {
            ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));
        }

        emit silient(isMuted);
    });

    ui->volumeBox->installEventFilter(this);
}

VolumeTool::~VolumeTool()
{
    delete ui;
}

void VolumeTool::paintEvent(QPaintEvent *event)
{
    (void)event;
    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QBrush(Qt::white));

    QPolygon polygon;
    QPoint a(10 + 12, 300);
    QPoint b(10 + 72, 300);
    QPoint c(10 + 42, 300 + 20);
    polygon.append(a);
    polygon.append(b);
    polygon.append(c);

    painter.drawPolygon(polygon);
}

bool VolumeTool::eventFilter(QObject* watched, QEvent* event)
{
    if(watched == ui->volumeBox)
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            calVolume();
        }
        else if(event->type() == QEvent::MouseButtonRelease)
        {
            emit setMusicVolume(volumeRatio);
        }
        else if(event->type() == QEvent::MouseMove)
        {
            calVolume();
            emit setMusicVolume(volumeRatio);
        }
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void VolumeTool::calVolume()
{
    //获取到屏幕的坐标，并将其转化为控件的坐标
    int height = ui->volumeBox->mapFromGlobal(QCursor().pos()).y();

    //鼠标在volumeBox中的移动范围
    height = height < 25 ? 25 : height;
    height = height > 205 ? 205 : height;

    //更新sliderButton的位置
    ui->sliderBtn->move(ui->sliderBtn->x(), height - ui->sliderBtn->height() / 2);

    //更新outline的大小
    ui->outLine->setGeometry(ui->outLine->x(), height, ui->outLine->width(), 205 - height);

    //计算音量比率
    volumeRatio = (int)((int)ui->outLine->height() / (float)180 * 100);

    //更新音量文本
    ui->volumeRatio->setText(QString::number(volumeRatio) + "%");
}

void VolumeTool::setSilent()
{
    ui->volumeRatio->setText("0%");
    ui->outLine->setGeometry(ui->outLine->x(), 205, ui->outLine->width(), 0);
    ui->sliderBtn->move(ui->sliderBtn->x(), 205);
}
